﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using Tisbi.LawFirm.DAL;
using Tisbi.LawFirm.DAL.Models;

namespace Tisbi.LawFirm.BL.Services.Implementation
{
    public class ServiceAgentBase<T> : IServiceAgentBase<T> where T : class
    {
        protected LawContext DataBaseContext {
            get { return DBContextManager.DataBaseContext; }
        }

        public virtual void GetItem(Action<List<T>, Exception> completed)
        {
            // Declare error and result
            Exception error = null;
            List<T> items = null;

            // Set error or result
            try
            {
                IQueryable<T> lawsuits = DataBaseContext.Set<T>();
                items = lawsuits.ToList();
            }
            catch (Exception ex)
            {
                error = ex;
            }

            // Invoke completion callback
            completed(items, error);
        }

        public virtual void AddItem(T item, Action<Exception> completed)
        {
            try
            {
                DataBaseContext.Set<T>().Add(item);
                DataBaseContext.SaveChanges();
                completed(null);
            }
            catch (Exception ex)
            {
                completed(ex);
            }
        }

        public virtual void RemoveItem(T item)
        {
            DataBaseContext.Set<T>().Remove(item);
            DataBaseContext.SaveChanges();
        }

        public virtual void Edit(T item, Action<Exception> completed)
        {
            try
            {
                DataBaseContext.Set<T>().Attach(item);
                DataBaseContext.Entry(item).State = EntityState.Modified;
                DataBaseContext.SaveChanges();
                completed(null);
            }
            catch (Exception ex)
            {
                completed(ex);
            }
        }

        public virtual void RejectChanges()
        {
            foreach (var entry in DataBaseContext.ChangeTracker
                .Entries<Cases>()
                .Where(e => e.State == EntityState.Modified))
            {
                entry.CurrentValues.SetValues(entry.OriginalValues);
            }
        }
    }
}
